<!--
@description: FieldMap.vue
@author: liujiabin01
@time:2025/5/16 15:54
-->

<template>
  <van-field :label="label" class="field-map">
    <template #input>
      <div class="field-map-box" style="width: 100%; height: 300px">
        <div ref="tengxun-map-box" style="width: 100%; height: 100%"></div>
        <div class="field-map-update-user-center" v-if="!disabled" @click="updateCenter"><van-icon name="location-o" /></div>
      </div>

    </template>
  </van-field>
</template>

<script>
import {Notify} from 'vant';

export default {
  name: 'FieldQRcode',
  props: {
    label: {
      type: String,
      default: '地图'
    },
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: true
    }
  },
  // 监听属性
  watch: {
    value () {
      if (this.disabled === false && this.map !== undefined) {
        // 修改地图中心点
        this.map.setCenter(new window.TMap.LatLng(this.centerY, this.centerX));
        this.markers.updateGeometries([
          {id: 'demo', styleId: 'marker1', position: new window.TMap.LatLng(this.centerY, this.centerX)}
        ])
      }
    }
  },
  data () {
    return {
      map: undefined,
      marker: [],
      userPositionInfo: {},
      userPositionX: '',
      userPositionY: ''
    }
  },
  computed: {
    latitude () {
      const lat = this.value && this.value.indexOf(',') >= 0 ? this.value.split(',')[0] : '39.903021'
      return lat
    },
    longitude () {
      const lon = this.value && this.value.indexOf(',') >= 0 ? this.value.split(',')[1] : '116.398430'
      return lon
    },
    centerX () {
      return this.longitude || this.userPositionX
    },
    centerY () {
      return this.latitude || this.userPositionY
    }
  },
  // 渲染执行
  mounted () {
    let _this = this
    _this.getUserPosition().then(res => {
      // 绘制地图
      let dom = _this.$refs['tengxun-map-box']
      _this.map = new window.TMap.Map(dom, {
        center: new window.TMap.LatLng(_this.centerY, _this.centerX),
        zoom: 12
      });

      // 添加标点
      _this.markers = new window.TMap.MultiMarker({
        map: this.map,
        styles: {
          marker1: new window.TMap.MarkerStyle({
            width: 20,
            height: 30,
            anchor: {x: 10, y: 30}
          })
        },
        geometries: [{
          id: 'demo',
          styleId: 'marker1',
          position: new window.TMap.LatLng(_this.centerY, _this.centerX)
        }]
      });

      //  Map实例创建后，通过on方法绑定点击事件
      _this.map.on('click', _this.clickHandler)
    })
  },
  methods: {
    getUserPosition () {
      return new Promise((resolve, reject) => {
        //  key ： 必填，开发密钥(key)，申请地址 https://lbs.qq.com/dev/console/key/manage
        //  referer： 必填，调用来源，一般为您的应用名称，
        let geolocation = new window.qq.maps.Geolocation('MNHBZ-YRBCZ-BK4X3-7UCU7-SZQ2O-L4BON', 'mapqq');
        geolocation.getLocation((params) => this.showPosition(params, resolve), (params) => this.errorPosition(params, resolve));
      })
    },
    showPosition (params, resolve) {
      this.userPositionX = params.lng
      this.userPositionY = params.lat
      this.userPositionInfo = params
      resolve()
    },
    errorPosition (params, resolve) {
      this.userPositionX = ''
      this.userPositionY = ''
      this.userPositionInfo = {}
      console.error(params, '获取用户当前地址失败')
      Notify({type: 'error', message: '获取用户当前地址失败'});
      resolve()
    },
    // 定义事件处理方法
    clickHandler (evt) {
      const lat = evt.latLng.getLat().toFixed(6);
      const lng = evt.latLng.getLng().toFixed(6);
      console.log('您点击的的坐标是：' + lat + ',' + lng);
      if (this.disabled === false) {
        this.$emit('change', lat + ',' + lng)
      }
    },
    updateCenter () {
      this.$emit('change', this.userPositionY + ',' + this.userPositionX)
    }
  }
}
</script>

<style scoped>
.field-map-box {
  position: relative;
}

.field-map-update-user-center {
  position: absolute;
  bottom: 20px;
  right: 30px;
  z-index: 1002;
  background-color: #fff;
  width: 40px;
  height: 40px;
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
  cursor: pointer;
}
</style>
